package com.newcapec.modules.pass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newcapec.common.utils.Constant;
import com.newcapec.common.utils.PageUtils;
import com.newcapec.common.utils.Query;
import com.newcapec.modules.health.entity.EducateDeptEntity;
import com.newcapec.modules.health.entity.StudentEntity;
import com.newcapec.modules.health.service.EducateDeptService;
import com.newcapec.modules.health.service.StudentService;
import com.newcapec.modules.pass.dao.WhiteListContentDao;
import com.newcapec.modules.pass.entity.WhiteListContentEntity;
import com.newcapec.modules.pass.service.WhiteListContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("whiteListContentService")
public class WhiteListContentServiceImpl extends ServiceImpl<WhiteListContentDao, WhiteListContentEntity> implements WhiteListContentService {

    @Autowired
    private EducateDeptService educateDeptService;
    @Autowired
    private StudentService studentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WhiteListContentEntity> page = this.baseMapper.selectPageVo(
                new Query<WhiteListContentEntity>().getPage(params, "id", false), params
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(WhiteListContentEntity whiteListContent) {
        Long customerId = whiteListContent.getCustomerId();
        Long deptId = whiteListContent.getDeptId();
        EducateDeptEntity educateDept = educateDeptService.getById(deptId);
        QueryWrapper<StudentEntity> queryWrapper = new QueryWrapper<>();
        if(educateDept.getLevel() == Constant.DeptLevel.UNIVERSITY.getValue()){
            queryWrapper.eq("customer_id", customerId);
        }else if(educateDept.getLevel() == Constant.DeptLevel.COLLEGE.getValue()){
            queryWrapper.eq("college_id", deptId);
        }else if(educateDept.getLevel() == Constant.DeptLevel.MAJOR.getValue()){
            queryWrapper.eq("major_id", deptId);
        }else if(educateDept.getLevel() == Constant.DeptLevel.CLASS.getValue()){
            queryWrapper.eq("class_id", deptId);
        }
        List<StudentEntity> studentList = studentService.list(queryWrapper);
        if(studentList==null || studentList.isEmpty()){
            return false;
        }
        List<String> stuNoList = studentList.stream().map(StudentEntity::getStuNo).collect(Collectors.toList());
        whiteListContent.setStuNoList(stuNoList);
        return this.baseMapper.insertBatch(whiteListContent) > 0;
    }

}